package com.ruoyi.index.userController;


import cn.hutool.core.date.DateTime;
import com.cyl.manager.ums.domain.entity.UserInfo;
import com.ruoyi.chat.service.IFhChatFriendService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.index.domain.FhIndexPostcomments;
import com.ruoyi.index.domain.FhIndexPostinfo;
import com.ruoyi.index.domain.PostcommentsLike;
import com.ruoyi.index.service.IFhIndexHotService;
import com.ruoyi.index.service.IFhIndexLikeService;
import com.ruoyi.index.service.IFhIndexPostcommentsService;
import com.ruoyi.index.service.IFhIndexPostinfoService;
import com.ruoyi.index.service.impl.FhIndexPostinfoDetailService;
import com.ruoyi.index.service.impl.IndexPostcommentsLikeService;
import com.ruoyi.info.domain.FhInfoExperience;
import com.ruoyi.info.domain.FhInfoUser;
import com.ruoyi.info.domain.FhInfoUsertask;
import com.ruoyi.info.service.*;
import com.ruoyi.map.service.IFhMapFishtypeService;
import com.ruoyi.map.service.IFhMapWaterService;
import com.ruoyi.tokenTools.UserLoginToken;
import com.ruoyi.web.core.config.LocalUserInfoUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 评论接口Controller
 *
 * @author ruoyi
 * @date 2024-11-11
 */
@Api(tags = "首页评论接口Controller")
@RestController
@RequestMapping("/app/index/postComments")
public class FhIndexPostcommentController extends BaseController {

    @Autowired
    private IFhIndexPostinfoService fhIndexPostinfoService;

    @Autowired
    private IFhIndexPostcommentsService iFhIndexPostcommentsService;

    @Autowired
    private IFhIndexLikeService iFhIndexLikeService;

    @Autowired
    private IFhChatFriendService iFhChatFriendService;

    @Autowired
    private IFhIndexHotService iFhIndexHotService;

    @Autowired
    private IFhInfoUserService fhInfoUserService;

    @Autowired
    private IFhInfoCatchrecordService fhInfoCatchrecordService;

    @Autowired
    private IFhInfoMyspaceService fhInfoMyspaceService;

    @Autowired
    private IFhInfoExperienceService fhInfoExperienceService;

    @Autowired
    private IFhMapFishtypeService fhMapFishtypeService;

    @Autowired
    private IFhInfoUsertaskService fhInfoUsertaskService;

    @Autowired
    private IFhInfoFishpointService fhInfoFishpointService;

    @Autowired
    private IFhMapWaterService fhMapWaterService;

    @Autowired
    private IFhChatFriendService fhChatFriendService;

    @Autowired
    private FhIndexPostinfoDetailService fhIndexPostinfoDetailService;

    @Autowired
    private FhInfoEquipService fhInfoEquipService;

    @Autowired
    private IndexPostcommentsLikeService indexPostcommentsLikeService;

    /**
     * 用户完成任务加积分
     */
    public R<String> compleTask(Long taskId)
    {
        try {
            //修改信息表
            Long userId = LocalUserInfoUtil.getLocalUserInfo().getId();
            FhInfoUser fhInfoUserInfo = fhInfoUserService.selectFhInfoUserByUserId(userId);
            Long points = fhInfoUserInfo.getPoints();
            points+=10;
            fhInfoUserInfo.setPoints(points);
            fhInfoUserService.updateFhInfoUser(fhInfoUserInfo);
            //修改任务表状态，1为未完成，0为完成
            FhInfoUsertask fhInfoUsertask = new FhInfoUsertask();
            fhInfoUsertask.setUserId(userId);
            fhInfoUsertask.setTaskId(taskId);
            fhInfoUsertask.setCompletionStatus("0");
            fhInfoUsertaskService.updateFhInfoUsertaskByUserIdAndTaskId(fhInfoUsertask);
            return R.ok("完成成功");
        }catch (Exception e){
            System.out.println(e.getMessage());
            return R.fail(e.getMessage());
        }
    }


    /**
     * 发布评论
     */
    @UserLoginToken
    @ApiOperation("发布评论")
    @PostMapping("/postComment")
    @Transactional
    public R<String> postComment(FhIndexPostcomments fhIndexPostcomments) {
        try {
            Long userId = LocalUserInfoUtil.getLocalUserInfo().getId();
            FhInfoUser fhInfoUser1 = fhInfoUserService.selectFhInfoUserByUserId(userId);
            //修改发布信息评论数量
            Long postinfoId = fhIndexPostcomments.getPostinfoId();
            FhIndexPostinfo fhIndexPostinfo = new FhIndexPostinfo();
            fhIndexPostinfo.setId(postinfoId);
            List<FhIndexPostinfo> fhIndexPostinfos = fhIndexPostinfoService.selectFhIndexPostinfoList(fhIndexPostinfo);
            Long comments = fhIndexPostinfos.get(0).getComments();
            comments += 1;
            fhIndexPostinfos.get(0).setComments(comments);
            fhIndexPostinfoService.updateFhIndexPostinfo(fhIndexPostinfos.get(0));
            //发布评论
            fhIndexPostcomments.setCommentId(userId);
            fhIndexPostcomments.setCrateTime(new Date());
            fhIndexPostcomments.setCommentName(fhInfoUser1.getName());
            //如果有回复id则插入回复人信息
            if(fhIndexPostcomments.getReplyCommentId()!=null){
                FhIndexPostcomments fhIndexPostcomments1 = iFhIndexPostcommentsService.selectFhIndexPostcommentsById(fhIndexPostcomments.getReplyCommentId());
                Long replyUserId = fhIndexPostcomments1.getCommentId();
                String commentName = fhIndexPostcomments1.getCommentName();
                fhIndexPostcomments.setReplyUserId(replyUserId);
                fhIndexPostcomments.setReplyUserName(commentName);
            }
            iFhIndexPostcommentsService.insertFhIndexPostcomments(fhIndexPostcomments);

            //发布评论成功后增加发布用户经验,如果用户经验超过10，则升一级
            FhInfoUser fhInfoUser = fhInfoUserService.selectFhInfoUserByUserId(userId);
            Long experience = fhInfoUser.getExperience();
            Long grade = fhInfoUser.getGrade();
            experience += 1;

            Long nextGrade = grade + 1;
            FhInfoExperience fhInfoExperience = fhInfoExperienceService.selectFhInfoExperienceById(nextGrade);
            Long experienceMax = fhInfoExperience.getExperienceMax();
            if (experience >= experienceMax) {
                grade += 1L;
                experience = 0L;
            }
            fhInfoUser.setExperience(experience);
            fhInfoUser.setGrade(grade);
            fhInfoUserService.updateFhInfoUser(fhInfoUser);

            //修改发布评论任务完成状态
            compleTask(3L);

            return R.ok("发布评论成功");
        } catch (Exception e) {
            //手工回滚异常
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.fail(e.getMessage());
        }
    }


    /**
     * 点赞评论
     */
    @UserLoginToken
    @ApiOperation("点赞评论")
    @PostMapping("/likeComment")
    @Transactional
    public R<String> likeComment(Long commentId) {
        try {
            Long userId = LocalUserInfoUtil.getLocalUserInfo().getId();
            PostcommentsLike postcommentsLike = new PostcommentsLike();
            postcommentsLike.setUserId(userId);
            postcommentsLike.setPostcommentsId(commentId);
            //插入点赞表
            indexPostcommentsLikeService.likePostcomments(postcommentsLike);
            //点赞数加一
            FhIndexPostcomments fhIndexPostcomments = iFhIndexPostcommentsService.selectFhIndexPostcommentsById(commentId);
            Long likes = fhIndexPostcomments.getLikeNum()+1;
            fhIndexPostcomments.setLikeNum(likes);
            iFhIndexPostcommentsService.updateFhIndexPostcomments(fhIndexPostcomments);
            return R.ok("点赞成功");
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.fail(e.getMessage());
        }
    }

    /**
     * 取消点赞评论
     */
    @UserLoginToken
    @ApiOperation("取消点赞评论")
    @DeleteMapping("/noLikeComment")
    @Transactional
    public R<String> noLikeComment(Long commentId) {
        try {
            Long userId = LocalUserInfoUtil.getLocalUserInfo().getId();
            PostcommentsLike postcommentsLike = new PostcommentsLike();
            postcommentsLike.setUserId(userId);
            postcommentsLike.setPostcommentsId(commentId);
            indexPostcommentsLikeService.unlikePostcomments(postcommentsLike);
            //点赞数减一
            FhIndexPostcomments fhIndexPostcomments = iFhIndexPostcommentsService.selectFhIndexPostcommentsById(commentId);
            Long likes = fhIndexPostcomments.getLikeNum()-1;
            fhIndexPostcomments.setLikeNum(likes);
            iFhIndexPostcommentsService.updateFhIndexPostcomments(fhIndexPostcomments);
            return R.ok("取消点赞成功");
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.fail(e.getMessage());
        }
    }


    /**
     * 分页获取评论
     */
    @UserLoginToken
    @ApiOperation("分页获取评论")
    @GetMapping("/getComments")
    public R<TableDataInfo> getComments(
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
            Long postInfoId,Long parentId) {
        try {
            UserInfo localUserInfo = LocalUserInfoUtil.getLocalUserInfo();
            List<FhIndexPostcomments> fhIndexPostcommentsList = new ArrayList<>();
            FhIndexPostcomments querComments = new FhIndexPostcomments();
            if(postInfoId!=null){
                querComments.setPostinfoId(postInfoId);
                startPage();
                fhIndexPostcommentsList = iFhIndexPostcommentsService.selectFhIndexPostcommentsList(querComments);
            }else {
                querComments.setParentId(parentId);
                startPage();
                fhIndexPostcommentsList = iFhIndexPostcommentsService.selectFhIndexPostcommentsList(querComments);
            }
            //插入用户信息，是否点赞，子评论数量,回复的用户信息
            for (FhIndexPostcomments fhIndexPostcomments : fhIndexPostcommentsList) {
                Long commentId = fhIndexPostcomments.getCommentId();
                //用户信息
                FhInfoUser fhInfoUser = fhInfoUserService.selectFhInfoUserByUserId(commentId);
                //子评论数量
                Long id = fhIndexPostcomments.getId();
                FhIndexPostcomments fhIndexPostcomments1 = new FhIndexPostcomments();
                fhIndexPostcomments1.setParentId(id);
                List<FhIndexPostcomments> fhIndexPostcommentsList1 = iFhIndexPostcommentsService.selectFhIndexPostcommentsList(fhIndexPostcomments1);
                int childCount = fhIndexPostcommentsList1.size();
                //是否点赞
                PostcommentsLike postcommentsLike = new PostcommentsLike();
                postcommentsLike.setUserId(localUserInfo.getId());
                postcommentsLike.setPostcommentsId(id);
                postcommentsLike.setCreateTime(new DateTime());
                PostcommentsLike likeStatus = indexPostcommentsLikeService.getLikeStatus(postcommentsLike);

                fhIndexPostcomments.setIsLike(likeStatus != null);
                fhIndexPostcomments.setChildCount((long) childCount);
                fhIndexPostcomments.setFhInfoUser(fhInfoUser);
                //判断是否存在回复的用户信息
                Long replyUserId = fhIndexPostcomments.getReplyUserId();
                if(replyUserId!=null){
                    FhInfoUser fhInfoUser1 = fhInfoUserService.selectFhInfoUserByUserId(replyUserId);
                    fhIndexPostcomments.setReplyUser(fhInfoUser1);
                }
            }
            return R.ok(getDataTable(fhIndexPostcommentsList));
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }
}
